package org.boge.sharpdoc.controller;

import com.github.pagehelper.PageInfo;
import org.boge.sharpdoc.config.Settings;
import org.boge.sharpdoc.bean.DocIcon;
import org.boge.sharpdoc.bean.LayuiReturnData;
import org.boge.sharpdoc.service.DocIconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("icon/admin")
public class IconController {
    @Autowired
    private DocIconService docIconService;
    @Autowired
    private Settings settings;

    @PostMapping("getIconList")
    @ResponseBody
    public LayuiReturnData getIconList(Integer index, Integer pageSize) {
        PageInfo<DocIcon> res = docIconService.getIconList(index, pageSize);
        return new LayuiReturnData(0, true, "数据查询成功！", res.getSize(), res.getList());
    }

    @PostMapping("uploadIcon")
    @ResponseBody
    public LayuiReturnData uploadIcon(MultipartFile file, String inputsuffix) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String filename = UUID.randomUUID() + suffix;
        File storedFile = new File(settings.getIconsDir(), filename);
        file.transferTo(storedFile);
        DocIcon docIcon = new DocIcon(inputsuffix, filename);
        return new LayuiReturnData(0, docIconService.addNewItem(docIcon));
    }

    @PostMapping("deleteIconItem")
    @ResponseBody
    public LayuiReturnData deleteIconItem(DocIcon docIcon) {
        docIconService.deleteItem(docIcon);
        return new LayuiReturnData(0, true);
    }

    @PostMapping("delByBatch")
    @ResponseBody
    public LayuiReturnData delByBatch(@RequestParam(value = "suffixes[]") String[] suffixes) {
        docIconService.delByBatch(suffixes);
        return new LayuiReturnData(0);
    }

    @GetMapping("setIconPage")
    public String setIconPage() {
        return "admin/setIcon";
    }
}